package com.biz.primus.ms.depot.dao.redis;

import com.biz.primus.base.redis.CrudRedisDao;
import com.biz.primus.base.redis.util.RedisUtil;
import com.biz.primus.common.utils.DateUtil;
import com.biz.primus.ms.depot.dao.ro.QrCodeRo;
import org.springframework.stereotype.Repository;

import java.sql.Timestamp;
import java.util.List;
import java.util.Set;

/**
 * QrCodeRedisDao
 *
 * @author JKLiues
 * @date 2017年11月07日
 */
@Repository
public class QrCodeRedisDao extends CrudRedisDao<QrCodeRo, Long> {

    @Override
    public void save(QrCodeRo ro) {
        super.save(ro);
        this.doMapping(ro);
    }

    private void doMapping(QrCodeRo ro) {
        Timestamp beginTime = ro.getBeginTime();
        Timestamp endTime = ro.getEndTime();
        boolean nowBetween = DateUtil.isNowBetween(beginTime, endTime);
        if (nowBetween) {
            this.addToEffective(ro.getId());
        }
    }

    public void initAndSetEffective(List<Long> ids) {
        String key = this.getEffectiveKey();
        super.del(key);
        ids.forEach(id -> super.sadd(key, RedisUtil.toByteArray(id)));
    }

    public void removeFromEffective(Long id) {
        String key = this.getEffectiveKey();
        super.srem(key, RedisUtil.toByteArray(id));
    }

    public void addToEffective(Long id) {
        String key = this.getEffectiveKey();
        super.srem(key, RedisUtil.toByteArray(id));
    }

    public List<QrCodeRo> getEffective() {
        String key = this.getEffectiveKey();
        Set<byte[]> idBytes = super.smembers(key);
        return super.findByIds(idBytes);
    }

    private String getEffectiveKey() {
        return getKeyByParams("effective");
    }
}